﻿using TMPro;
using UnityEngine;

public class StatsUI : MonoBehaviour
{
    [SerializeField]
    TextMeshProUGUI moneyText,
        levelText,
        remainTimeText;
    [SerializeField] GameObject heartPrefab;
    [SerializeField] Transform healthTF;
    private void Start()
    {   
        for(int i = 0; i < Knight.Instance.Health; i++)
        {
            Instantiate(heartPrefab, healthTF);
        }        
        moneyText.text = Knight.Instance.Money.ToString();
        levelText.text = LevelManager.Instance.Level.ToString();
        remainTimeText.text = LevelManager.Instance.Duration.ToString();
    }

    private void OnEnable()
    {
        MyEvenSystem.OnPlayerHealthChanged += UpdateHealth;
        MyEvenSystem.OnPlayerMoneyChanged += UpdateMoney;
        MyEvenSystem.OnLevelRemainTimeChanged += UpdateRemainTime;
        MyEvenSystem.OnLevelChanged += UpdateLevel;
    }

    private void OnDisable()
    {
        MyEvenSystem.OnPlayerHealthChanged -= UpdateHealth;
        MyEvenSystem.OnPlayerMoneyChanged -= UpdateMoney;
        MyEvenSystem.OnLevelRemainTimeChanged -= UpdateRemainTime;
        MyEvenSystem.OnLevelChanged -= UpdateLevel;
    }

    void UpdateHealth(int health)
    {
        if(health<0)
        {                                                                        
            for(int i= healthTF.childCount-1; i>=0 && health < 0; i++)
            {
                Destroy(healthTF.GetChild(i).gameObject);
                health++;
            }                
        }
        else if(health>0)
        {
            for(int i=0;i<health;i++)
                Instantiate(heartPrefab, healthTF);
        }        
    }

    void UpdateMoney(int money)
    {
        moneyText.text = money.ToString();
    }

    private void UpdateLevel(int level)
    {
        levelText.text = level.ToString();
    }

    void UpdateRemainTime(int time)
    {
        remainTimeText.text = time.ToString();
    }
}